package com.example.demo.sys.service.impl;

import com.example.demo.sys.common.LevelUtil;
import com.example.demo.sys.dto.DeptLevelDto;
import com.example.demo.sys.mapper.SysDeptMapper;
import com.example.demo.sys.model.SysDept;
import com.example.demo.sys.service.SysDeptService;
import com.example.demo.sys.service.SysTreeService;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import org.apache.commons.collections.MultiMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * Created by 蔡超 on 2018/10/7.
 */
@Service
public class SysTreeServiceImpl implements SysTreeService {
    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Override
    public List<DeptLevelDto> deptTree(){
        List<SysDept> sysDeptList = sysDeptMapper.selectAll();
        List<DeptLevelDto> levelDtoList = new ArrayList<DeptLevelDto>();
        for (SysDept sysDept : sysDeptList) {
            DeptLevelDto deptLevelDto = DeptLevelDto.adapt(sysDept);
            levelDtoList.add(deptLevelDto);
        }
        return deptListToTree(levelDtoList);
    }

    private List<DeptLevelDto> deptListToTree(List<DeptLevelDto> levelDtoList) {
        if(CollectionUtils.isEmpty(levelDtoList)){
            return new ArrayList<DeptLevelDto>();
        }
        //multimap 结构： key->[dept1,dept2,dept3]
        Multimap<Integer,DeptLevelDto> multimap = ArrayListMultimap.create();
        List<DeptLevelDto> rootList  = new ArrayList<>();

        for (DeptLevelDto levelDto : levelDtoList) {
            multimap.put(levelDto.getLevel(),levelDto);
            if(LevelUtil.ROOT.equals(levelDto.getLevel())){
                rootList.add(levelDto);
            }
        }

        //按照SQL,从小到大排序
        Collections.sort(rootList, deptSeqComparator);

        //递归排序
        transformDeptTree(rootList,LevelUtil.ROOT,multimap);
        return rootList;
    }

    /**
    * @Description:
     * 1、遍历该层的没个元素
     * 2、处理当前层级的元素
     * 3、处理下一层
    * @Param:
    * @return:
    * @Author: 蔡超
    * @Date: 2018/10/7 11:56
    */
    private void transformDeptTree(List<DeptLevelDto> rootList, int level, Multimap<Integer, DeptLevelDto> multimap) {
        for (DeptLevelDto deptLevelDto : rootList) {
            int nextLevel = LevelUtil.calculateLevel(level,deptLevelDto.getId());
        }
    }

    public Comparator<DeptLevelDto> deptSeqComparator = new Comparator<DeptLevelDto>() {
        @Override
        public int compare(DeptLevelDto o1, DeptLevelDto o2) {
            return o1.getSeq() - o2.getSeq();
        }
    };

}
